<?php
defined('IN_XLP') or exit('Access Denied');

class sellerModel extends Model {

    private static $wx = null;

    function __construct() {
        parent::__construct();
    }

    private function _msgInit() {

        if(empty(self::$wx)) {
            T('weixin/weixin.api');
            $setting = F('weixin/setting');
            self::$wx = new weixinMsgApi(array(
                'appid' => $setting['user_info']['wx_AppId'],
                'appsecret' => $setting['user_info']['wx_AppSecret']
            ));
        }
        
    }

    /*
     * 生成5位商户码
     */
    public function genSellerCode($uid) {
        $seller_code = strtoupper(base_convert($uid, 10, 36));
        $code_len    = strlen($seller_code);
        if($code_len < 5) {
            //补齐5位
            $random = strtoupper(substr(md5(TIME), 0, 5 - $code_len));
            $seller_code .= $random;
        }

        return $seller_code;
    }

    /*
     * 发送给用户消息
     */
    public function sendToUser($uid, $msg) {
        $this->_msgInit();
        $open_id = D('member')->getOpenidByUids($uid);

        $sendInfo = array(
            'touser' => $open_id,
            'msgtype' => 'text',
            'text' => array(
                'content' => $msg
            )
        );

        if (!self::$wx->sendCustomMessage($sendInfo)) {
            $err = array('status' => 0, 'code' => $weixinMsgApi->errCode, 'msg' => $weixinMsgApi->errMsg);
            saveLog('weixin/sale_code', $err);
        }
    }

}